package com.simemg.reader;

import com.simemg.reader.model.Loading;
import com.simemg.reader.provider.BookListProvider;
import com.simemg.reader.provider.BookNameListProvider;
import com.simemg.reader.store.Book;
import com.simemg.reader.utils.*;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.service.Window;
import ohos.multimodalinput.event.KeyEvent;

import java.util.ArrayList;
import java.util.List;

public class SearchAbility extends Ability {
    private boolean searching = false;

    private DirectionalLayout layout;
    private TextField input;
    private Button search;
    private Button delete;
    private ListContainer bookListContainer;
    private ListContainer bookNameListContainer;

    private final List<Book> bookList = new ArrayList<>();
    private final List<String> bookNameList = new ArrayList<>();

    private BookListProvider bookListProvider;
    private BookNameListProvider bookNameListProvider;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_search);
        setStatusBarMaroon();

        initComponent();
        loadData(intent);
        addComponentListen();
    }

    void loadData(Intent intent) {
        String name = (String) RouterUtil.getData(intent);
        if (name != null) {
            input.setText(name);
            delete.setPressState(true);
            getMainTaskDispatcher().delayDispatch(()-> updateBookList(name), 500);
        }
    }

    void initComponent() {
        input = (TextField) findComponentById(ResourceTable.Id_input);
        search = (Button) findComponentById(ResourceTable.Id_search);
        delete = (Button) findComponentById(ResourceTable.Id_delete);
        bookListContainer = (ListContainer) findComponentById(ResourceTable.Id_book_list);
        bookNameListContainer = (ListContainer) findComponentById(ResourceTable.Id_bookname_list);
        layout = (DirectionalLayout)findComponentById(ResourceTable.Id_layout);

        bookNameListProvider = new BookNameListProvider(bookNameList, getContext());
        bookNameListContainer.setItemProvider(bookNameListProvider);

        bookListProvider = new BookListProvider(bookList, getContext());
        bookListContainer.setItemProvider(bookListProvider);
    }

    void addComponentListen() {
        input.addTextObserver((content, start, before, count) -> {
            clearResult();
            boolean change = !content.equals("");
            if (change) updateBookNameList(content);
            delete.setPressState(change);
        });
        input.setKeyEventListener((component, event)-> {
            if (event.isKeyDown() && event.getKeyCode() == KeyEvent.KEY_ENTER) {
                clearResult();
                updateBookList(input.getText());
                return true;
            }
            return false;
        });
        search.setClickedListener(component -> {
            clearResult();
            if (!input.getText().equals("")) updateBookList(input.getText());
        });
        delete.setClickedListener(component -> input.setText(""));
        bookNameListContainer.setItemClickedListener((listContainer, component, i, l) -> {
            if (searching) return;
            String name = bookNameList.get(i);
            input.setText(name);
            clearResult();
            updateBookList(name);
        });
        bookListContainer.setItemClickedListener((listContainer, component, i, l) -> {
            Book book = bookList.get(i);
            LogUtil.info("点击了小说:" + book.getName());
            RouterUtil.toAbility(this, ".InfoAbility", book);
        });
    }

    void clearResult() {
        bookNameList.clear();
        bookNameListProvider.notifyDataChanged();
        bookList.clear();
        bookListProvider.notifyDataChanged();
    }

    void updateBookNameList(String name) {
        List<String> urls = new ArrayList<String>(){{
            add("http://81.69.18.37/SearchBook.aspx?keywords="+name); // 从旧版App上抓下来的两个链接，直接拿来用了
            add("http://81.69.18.37/NovelWebService.asmx/GetNovelNameList?keyWord="+name);
        }};
        RequestUtil.Get(urls)
                .setContext(getContext())
                .onSuccess((RequestUtil.CallBackMapString) result -> {
                    bookNameList.addAll(SpiderUtil.decodeName1(result.get(0)));
                    bookNameList.addAll(SpiderUtil.decodeName2(result.get(1)));
                    if (!searching) bookNameListProvider.notifyDataChanged();
                })
                .execute();
    }

    void updateBookList(String name) {
        LogUtil.info("搜索书名："+name);
        searching = true;
        Loading.show(layout);
        RequestUtil.Do(SpiderUtil.getSearchBooks(name))
                .setContext(getContext())
                .onSuccess((RequestUtil.CallBackMapObject)(result)->{
                    for (Integer i:result.keySet()) if(result.get(i) != null) {
                        List<Book> list = (List<Book>)result.get(i);
                        bookList.addAll(list);
                    }
                    bookListProvider.notifyDataChanged();
                    searching = false;
                    Loading.hide(layout);

                    // 更新书内容
                    updateBookListInfo();
                })
                .execute();
    }

    void updateBookListInfo() {
        RequestUtil.Do(SpiderUtil.getSearchBookInfo(bookList))
                .setContext(getContext())
                .onSuccess((RequestUtil.CallBackMapObject) (result)->{
                    for (Integer i:result.keySet()) if(result.get(i) != null){
                        Book newBook = (Book)result.get(i);
                        int size = bookList.size();
                        for(int j=0;j<size;j++) {
                            Book nowBook = bookList.get(j);
                            if (newBook.getLink().equals(nowBook.getLink())) {
                                bookList.set(j, newBook);
                            }
                        }
                    }
                    bookListProvider.notifyDataChanged();
                })
                .execute();

    }

    void setStatusBarMaroon() {
        Window window = getWindow();
        window.setStatusBarColor(ColorUtil.get(this, ResourceTable.Color_maroon));
        window.setStatusBarVisibility(Component.VISIBLE);
    }
}
